package com.atguigu.gulimall.product.service.impl;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SearchFeignService searchFeignService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );
        return new PageUtils(page);
    }
    /**
     * //TODO 高级部分完善
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {    //  发布商品接口
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity(); //  创建对象
        BeanUtils.copyProperties(vo,spuInfoEntity); //  赋值
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);//  添加到数据库
        //2、保存Spu的描述图片 pms_spu_info_desc
//        List<String> decript = vo.getDecript();
//        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
//        descEntity.setSpuId(infoEntity.getId());
//        descEntity.setDecript(String.join(",",decript));
//        spuInfoDescService.saveSpuInfoDesc(descEntity);
        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);  // 保存到数据库
        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();




        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> { //   遍历 baseAttrs

            ProductAttrValueEntity productAttrValueEntity= new ProductAttrValueEntity(); //  创建对象,对应的是pms_product_attr_value表,这个是规格属性,不是销售属性

            productAttrValueEntity.setAttrId(attr.getAttrId());  // 赋值

            AttrEntity attrEntity = attrService.getById(attr.getAttrId());  //   根据属性id,获取属性详细信息


            productAttrValueEntity.setAttrName(attrEntity.getAttrName()); //  赋值

            productAttrValueEntity.setAttrValue(attr.getAttrValues());  //  赋值

            productAttrValueEntity.setQuickShow(attr.getShowDesc()); // 赋值
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());  //   赋值
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        //  刚才生成的collect,代表的是,这款spu,所有的属性



        productAttrValueService.saveProductAttr(collect); //  保存到数据库



        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds





        Bounds bounds = vo.getBounds();  //  获取值


        SpuBoundTo spuBoundTo = new SpuBoundTo();     //  创建对象

        BeanUtils.copyProperties(bounds,spuBoundTo); //  赋值


        spuBoundTo.setSpuId(spuInfoEntity.getId());  //  赋值



        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }




        //5、保存当前spu对应的所有sku信息；
        List<Skus> skus = vo.getSkus();



        if(skus!=null && skus.size()>0){
            skus.forEach(item->{   //  遍历sku
                String defaultImg = "";   // 默认图片



                for (Images image : item.getImages()) { //  遍历单个sku的图片集
                    if(image.getDefaultImg() == 1){  // 如果 这个图片被前端标记为 sku默认图片的话
                        defaultImg = image.getImgUrl(); // 赋值
                    }
                }
//  所以上面这个for循环的作用就是,找出默认图片


                //    private String skuName;
                //    private BigDecimal price;
                //    private String skuTitle;
                //    private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();//对应 pms_sku_info 表

                BeanUtils.copyProperties(item,skuInfoEntity);  //  赋值
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());  //  赋值
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId()); //  赋值
                skuInfoEntity.setSaleCount(0L); //  设置 销量为0, 但是 销量也没有变过啊!!  当卖出一个sku时,销量也没有修改啊!!!
                skuInfoEntity.setSpuId(spuInfoEntity.getId());  //赋值
                skuInfoEntity.setSkuDefaultImg(defaultImg);  // 赋值   TODO   图片在这里!!!!1


                //5.1）、sku的基本信息；pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity); //  保存到数据库



                Long skuId = skuInfoEntity.getSkuId(); //   拿到sku_id


                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {  //  遍历单个sku的图片集
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity(); //  创建对象
                    skuImagesEntity.setSkuId(skuId); // 赋值
                    skuImagesEntity.setImgUrl(img.getImgUrl());  //  赋值
                    skuImagesEntity.setDefaultImg(img.getDefaultImg()); // 赋值
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true就是需要，false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());

                skuImagesService.saveBatch(imagesEntities);
                //TODO 没有图片路径的无需保存


                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity(); //  创建销售属性对象
                    BeanUtils.copyProperties(a, attrValueEntity);//  赋值
                    attrValueEntity.setSkuId(skuId); //  赋值
                    return attrValueEntity;
                }).collect(Collectors.toList());  //  销售属性合集

                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities); //  保存




                // //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price

                SkuReductionTo skuReductionTo = new SkuReductionTo(); //  创建  满减  对象

                BeanUtils.copyProperties(item,skuReductionTo); // 赋值

                skuReductionTo.setSkuId(skuId);  // 赋值

                if(skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){//  如果等于1,说明不想等.

                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);

                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }


                }
            });
        }
    }
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        /**
         * status: 2
         * key:
         * brandId: 9
         * catelogId: 225
         */
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }
    @Override
    public void up(Long spuId) {
       List<SkuInfoEntity>  skus=  skuInfoService.getSkusBySpuId(spuId);  //   查出当前spu_id对应的所有sku信息

        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());  //  获取 所有sku的id,放在一个数组里面
        //   还要:  查询当前sku的所有规格属性 注意:只查询 可以被检索 的规格属性

        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId);   //   查询规格属性,  放在一个数组里面




        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());    //  把 每个规格属性的id ,放在一个数组里面








        List<Long>  searchAttrIds=attrService.selectSearchAttrIds(attrIds);  //   根据这些规格属性的id,去查询什么?  为什么还要查询一遍?




        Set<Long>  idSet=new HashSet<>(searchAttrIds);    //    然后又把  规格属性的  id,放在一个set集合里面?  这是为什么?



        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
                    return idSet.contains(item.getAttrId());     //   把   符合idSet.contains(item.getAttrId()) 的留下
                }).map(item -> {
                    SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs1);
                    return attrs1;
                })
                .collect(Collectors.toList());    //    这 又是在做什么????


        Map<Long,Boolean> stockMap =null;    // 创建一个map集合,    key  是?: sku_id    value是?:  是否有库存





//             然后要:  发送远程调用,   去库存系统查看是否有库存
        try {
            R r = wareFeignService.getSkuHasStock(skuIdList);    //    根据  每个sku的id,去查询什么?  去查询 这个sku 还有没有 货 啦!!!
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));  // 我就知道: 他要转成键值对,哈哈哈哈
        }catch (Exception e){
            log.error("库存服务查询异常:原因{}",e);
        }


        Map<Long, Boolean> finalStockMap = stockMap;  //  ?? 怎么又做无用功?


        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();  //  创建对象
            BeanUtils.copyProperties(sku,esModel); //  赋值
            esModel.setSkuPrice(sku.getPrice());  //  赋值
            esModel.setSkuImg(sku.getSkuDefaultImg());  //   赋值

            if(finalStockMap ==null){  //  如果等于空?
                esModel.setHasStock(true);  //  如果等于空,直接给他赋值true,代表有库存.
            }else{  //   如果不等于空,  那肯定不等于空啊
        esModel.setHasStock(finalStockMap.get(sku.getSkuId())); //   赋值
            }
esModel.setHotScore(0L);   //  赋值
            //还要:    查询 品牌和  分类的名字信息
            BrandEntity brand= brandService.getById(esModel.getBrandId());  //   根据品牌id,查询品牌详情
            esModel.setBrandName(brand.getName()); //   赋值
            esModel.setBrandImg(brand.getLogo()); //   赋值
            CategoryEntity category = categoryService.getById(esModel.getCatalogId());  //  根据分类id,查询分类详情
            esModel.setCatalogName(category.getName());  //    赋值
esModel.setAttrs(attrsList);   // 赋值
            return esModel;
        }).collect(Collectors.toList());     //   然后 把 数据 都变成了 在elasticSearch里面存放的对象.

        R r = searchFeignService.productStatusUP(upProducts);  //   然后: 上架!!!!!
        if(r.getCode()==0) {
//     远程调用成功了, 要 修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
        }
    }
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfo = getById(spuId);
        return spuInfo;
    }
}